package com.ptu.util;

import cn.hutool.core.util.StrUtil;
import com.ptu.dto.UserDTO;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 获取请求头中的token
        String token = request.getHeader("authorization");
        System.out.println("JwtAuthenticationInterceptor token：" + token);

        // 2. 如果请求头中没有token，直接放行（可能是公开接口）
        if (StrUtil.isBlank(token)) {
            return true;
        }

        // 3. 验证token
        if (!jwtUtil.validateToken(token)) {
            return false;
        }

        // 4. 解析token中的用户信息
        Claims claims = jwtUtil.parseToken(token);
        UserDTO userDTO = new UserDTO();
        userDTO.setId(Integer.parseInt(claims.get("userId").toString()));
        userDTO.setUsername(claims.get("username").toString());
        userDTO.setPhone(claims.get("phone").toString());

        // 5. 将用户信息保存到ThreadLocal
        UserHolder.saveUser(userDTO);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 移除用户信息，防止内存泄漏
        System.out.println("afterCompletion移除 UserHolder 中的用户信息");
        UserHolder.removeUser();
    }
}